"""
ReAct 流式处理器 - 支持结构化流式输出的ReAct推理系统
"""

import json
import logging
import asyncio
from typing import Dict, Any, AsyncGenerator, List, Optional
from datetime import datetime

from app.core.react.react_controller import ReActController
from app.core.react.tools.intent_analysis_tool import IntentAnalysisTool
from app.core.react.tools.safety_check_tool import SafetyCheckTool
from app.core.react.tools.knowledge_retrieval_tool import KnowledgeRetrievalTool
from app.core.react.tools.context_retrieval_tool import ContextRetrievalTool

logger = logging.getLogger(__name__)


class ReActStreamProcessor:
    """ReAct流式处理器 - 支持结构化流式输出"""
    
    def __init__(self, db_session=None):
        """初始化ReAct流式处理器"""
        self.db_session = db_session
        self.react_controller = ReActController()
        self.max_iterations = 5
        self.step_timeout = 30  # 每步超时时间（秒）
        
    async def process_message_stream(
        self, 
        user_input: str, 
        user_id: str = None,
        chat_history: List[Dict[str, str]] = None
    ) -> AsyncGenerator[Dict[str, Any], None]:
        """
        流式处理用户消息，返回结构化的ReAct推理步骤
        
        Args:
            user_input: 用户输入
            user_id: 用户ID
            chat_history: 对话历史
            
        Yields:
            Dict: 结构化的推理步骤，格式为：
            {
                "type": "think|action|observation|final_answer",
                "content": "具体内容",
                "metadata": {...}
            }
        """
        try:
            logger.info(f"[ReActStream] 开始处理消息: {user_input[:50]}...")
            
            # 初始化ReAct状态
            react_state = {
                "user_input": user_input,
                "user_id": user_id,
                "chat_history": chat_history or [],
                "thoughts": [],
                "actions": [],
                "observations": [],
                "final_answer": None,
                "metadata": {
                    "emotion": "unknown",
                    "confidence": 0.5,
                    "crisis_level": "low",
                    "safety_triggered": False,
                    "tools_used": [],
                    "iteration_count": 0,
                    "start_time": datetime.now().isoformat()
                }
            }
            
            # 开始ReAct推理循环
            for iteration in range(self.max_iterations):
                react_state["metadata"]["iteration_count"] = iteration + 1
                
                # 步骤1: 思考 (Think)
                yield {
                    "type": "think",
                    "content": f"正在分析您的问题... (第{iteration + 1}轮推理)",
                    "metadata": {
                        "iteration": iteration + 1,
                        "timestamp": datetime.now().isoformat()
                    }
                }
                
                # 生成思考和行动
                thought_action = await self._generate_thought_action(react_state)
                
                # 输出思考内容
                if thought_action.get("thought"):
                    yield {
                        "type": "think",
                        "content": thought_action["thought"],
                        "metadata": {
                            "iteration": iteration + 1,
                            "timestamp": datetime.now().isoformat()
                        }
                    }
                    react_state["thoughts"].append(thought_action["thought"])
                
                # 检查是否需要执行行动
                if thought_action.get("action") and thought_action.get("action") != "finish":
                    # 步骤2: 行动 (Action)
                    action_name = thought_action["action"]
                    action_input = thought_action.get("action_input", "")
                    
                    yield {
                        "type": "action",
                        "content": f"执行工具: {action_name}",
                        "metadata": {
                            "action_name": action_name,
                            "action_input": action_input,
                            "iteration": iteration + 1,
                            "timestamp": datetime.now().isoformat()
                        }
                    }
                    
                    # 执行行动
                    observation = await self._execute_action(action_name, action_input, react_state)
                    
                    # 步骤3: 观察 (Observation)
                    yield {
                        "type": "observation",
                        "content": observation.get("result", "执行完成"),
                        "metadata": {
                            "action_name": action_name,
                            "observation_data": observation,
                            "iteration": iteration + 1,
                            "timestamp": datetime.now().isoformat()
                        }
                    }
                    
                    react_state["actions"].append({
                        "action": action_name,
                        "input": action_input
                    })
                    react_state["observations"].append(observation)
                    
                    # 更新元数据
                    if "emotion" in observation:
                        react_state["metadata"]["emotion"] = observation["emotion"]
                    if "confidence" in observation:
                        react_state["metadata"]["confidence"] = observation["confidence"]
                    if "crisis_level" in observation:
                        react_state["metadata"]["crisis_level"] = observation["crisis_level"]
                    if "safety_triggered" in observation:
                        react_state["metadata"]["safety_triggered"] = observation["safety_triggered"]
                
                else:
                    # 推理完成，生成最终答案
                    break
            
            # 步骤4: 生成最终答案 (Final Answer)
            final_answer = await self._generate_final_answer(react_state)
            
            yield {
                "type": "final_answer",
                "content": final_answer,
                "metadata": {
                    "total_iterations": react_state["metadata"]["iteration_count"],
                    "emotion": react_state["metadata"]["emotion"],
                    "confidence": react_state["metadata"]["confidence"],
                    "crisis_level": react_state["metadata"]["crisis_level"],
                    "safety_triggered": react_state["metadata"]["safety_triggered"],
                    "tools_used": react_state["metadata"]["tools_used"],
                    "end_time": datetime.now().isoformat()
                }
            }
            
            react_state["final_answer"] = final_answer
            
        except Exception as e:
            logger.error(f"[ReActStream] 处理失败: {e}")
            yield {
                "type": "error",
                "content": f"抱歉，我在处理您的消息时遇到了问题：{str(e)}",
                "metadata": {
                    "error": str(e),
                    "timestamp": datetime.now().isoformat()
                }
            }
    
    async def _generate_thought_action(self, react_state: Dict[str, Any]) -> Dict[str, str]:
        """生成思考和行动"""
        try:
            # 使用现有的ReAct控制器生成思考和行动
            result = await self.react_controller._generate_thought_action(react_state)
            return result
        except Exception as e:
            logger.error(f"[ReActStream] 生成思考行动失败: {e}")
            return {
                "thought": "我需要仔细分析您的问题...",
                "action": "intent_analysis",
                "action_input": react_state["user_input"]
            }
    
    async def _execute_action(self, action_name: str, action_input: str, react_state: Dict[str, Any]) -> Dict[str, Any]:
        """执行行动"""
        try:
            # 使用现有的ReAct控制器执行行动
            result = await self.react_controller._execute_action(action_name, action_input, react_state)
            
            # 记录使用的工具
            if action_name not in react_state["metadata"]["tools_used"]:
                react_state["metadata"]["tools_used"].append(action_name)
            
            return result
        except Exception as e:
            logger.error(f"[ReActStream] 执行行动失败: {e}")
            return {
                "result": f"执行工具 {action_name} 时出现错误: {str(e)}",
                "error": True
            }
    
    async def _generate_final_answer(self, react_state: Dict[str, Any]) -> str:
        """生成最终答案"""
        try:
            # 使用现有的ReAct控制器生成最终答案
            result = await self.react_controller._generate_final_answer(react_state)
            return result
        except Exception as e:
            logger.error(f"[ReActStream] 生成最终答案失败: {e}")
            return "抱歉，我在生成回复时遇到了问题。请您稍后再试，或者换个方式描述您的问题。"
    
    def _format_chat_history(self, chat_history: List[Dict[str, str]]) -> str:
        """格式化对话历史"""
        if not chat_history:
            return "无对话历史"
        
        formatted = []
        for msg in chat_history[-5:]:  # 只取最近5条
            role = msg.get("role", "unknown")
            content = msg.get("content", "")
            formatted.append(f"{role}: {content}")
        
        return "\n".join(formatted)
